package cn.sxgan.gen.controller;

import cn.sxgan.gen.enums.DataSourceType;
import cn.sxgan.gen.model.GlobalDataSource;
import cn.sxgan.gen.services.base.DataSourceSwitcherService;
import cn.sxgan.gen.utils.CommonUtils;
import cn.sxgan.gen.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/datasource")
public class DataSourceController {
    
    @Autowired
    private DataSourceSwitcherService switcherService;
    
    @PostMapping("/switch")
    public Result<String> switchDataSource(@RequestBody GlobalDataSource globalDataSource) {
        try {
            String dbUrl = CommonUtils.getDbUrl(globalDataSource);
            DataSourceType dataSourceType = DataSourceType.getEnumValue(globalDataSource.getDbType());
            if (dataSourceType == null) {
                return Result.fail("不支持的数据库类型");
            }
            switcherService.switchDataSource(
                    globalDataSource.getKey(),
                    dbUrl,
                    globalDataSource.getUsername(),
                    globalDataSource.getPassword(),
                    dataSourceType.getDriverClass()
            );
            return Result.success("数据源切换成功");
        } catch (Exception e) {
            return Result.fail("切换失败: " + e.getMessage());
        }
    }
    
    @PostMapping("/default")
    public ResponseEntity<String> revertToDefault() {
        switcherService.switchToDefault();
        return ResponseEntity.ok("已切换回默认数据源");
    }
}